package com.example.springbootdockertest.controller.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 票
 *
 * @Author liguangcheng
 * @Date 2022/2/15 10:28 上午
 * @Vision 1.0
 **/
public class Ticket {
    // 属性、方法
    private int number = 3000;

    Lock lock = new ReentrantLock();

    // 卖票的方式
    public void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票,剩余：" + number);
        }

    }

    // synchronized 本质: 队列，锁
    public synchronized void synSale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票,剩余：" + number);
        }

    }

    public void lockSale() {
        lock.lock();
        // 加锁
        try {// 业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票,剩余：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            // 解锁
        }
    }
}
